<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class PaperCommit extends Model
{
    use SoftDeletes;
    protected $table = 'paper_commits';

    /**
     * 定义主键
     * @var string
     */
    protected $primaryKey = 'id';

    /**
     * 禁止批量赋值的字段
     *
     * @var array
     */
    protected $guarded = ['id','created_at','deleted_at'];

    /**
     * 软删除应该被调整为日期的属性
     * [$dates description]
     * @var [type]
     */
    protected $dates=[
        'created_at', 'updated_at','deleted_at'
    ];

    // 存储试卷
    public static function store($param){

        if(!$user_id = auth() -> id()){

            $user_id = User::where('phone_num',$param['mobile']) -> value('id');
            if(!$user_id){
                $data = [
                    'real_name' => $param['real_name'],
                    'user_name' => str_replace(substr($param['mobile'],3,4),'****',$param['mobile']),
                    'phone_num' => $param['mobile'],
                    'head_portrait' => 'default/headpic.png',
                ];
                $user_id = User::create($data)->id;
                // 注册成功，添加积分
                IntegralRule::rule(1,$user_id);
            }
        }

        $answer = json_decode($param['answer']);
        $paper_librarie_id = $param['paper_librarie_id'];

        $res = self::answerDeal($paper_librarie_id, $answer, $user_id, ($param['region_id']?? 0));

        //  问卷答题人数自增
        if($res){
            PaperLibrary::where('id',$paper_librarie_id) -> increment('answer_user_num');
        }
        return $res;
    }




    /*
     * 针对答案进行处理
     *
     * $answer = [
             '12' => ['A'],
             '13' => ['A','B']
        ];
     * */
    public static function answerDeal($paper_librarie_id,$answer,$user_id,$region_id = 0)
    {
        $batch_num = uniqid(time());

        $arr = [];
        foreach($answer as $k => $v){

            $arr = [
                'paper_librarie_id' => $paper_librarie_id,
                'paper_feedback_id' => $k,
                'answer'    => json_encode($v,true),
                'user_id'   => $user_id,
                'region_id' => $region_id,
                'batch_num' => $batch_num
            ];
            $res = self::create($arr);

        }

        return $res;

    }
}
